package com.csu.soa_library.controller;

import com.csu.soa_library.common.CommonResponse;
import com.csu.soa_library.entity.Book;
import com.csu.soa_library.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.util.ArrayList;
import java.util.List;

/**
 * @author YiGongLily
 * @version V1.0
 * Copyright (c) 2024, bie blind copy all thing fine.
 * @ProjectName:soa_library
 * @Title: BookController
 * @Package com.csu.soa_library.controller
 * @Description: book_c
 * @date 2024/11/25 23:19
 */
@RestController
public class BookController {
    private final BookService bookService;

    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    private List<CommonResponse.Link> createLinks() {
        List<CommonResponse.Link> links = new ArrayList<>();

        links.add(new CommonResponse.Link("add-book", "http://localhost:8081/api/books", "POST"));
        links.add(new CommonResponse.Link("delete-book", "http://localhost:8081/api/books/{bookId}", "DELETE"));
        links.add(new CommonResponse.Link("bookInfo", "http://localhost:8081/api/books/{bookId}", "GET"));
        links.add(new CommonResponse.Link("update-book", "http://localhost:8081/api/books/{bookId}", "PUT"));
        links.add(new CommonResponse.Link("bookPage", "http://localhost:8081/api/books", "GET"));

        return links;
    }

    private String convertToXml(Book book, List<CommonResponse.Link> links) {
        try {
            XmlMapper xmlMapper = new XmlMapper();
            CommonResponse.DataWrapper2<Book> dataWrapper = new CommonResponse.DataWrapper2<>(book, links);
            return xmlMapper.writeValueAsString(dataWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    private String convertToXml(CommonResponse<?> response) {
        try {
            XmlMapper xmlMapper = new XmlMapper();
            return xmlMapper.writeValueAsString(response);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 添加书籍
    @PostMapping("/books")
    public Object addBook(@RequestBody Book book, @RequestParam(defaultValue = "1") String format) {
        bookService.addBook(book);
        List<CommonResponse.Link> links = createLinks();

        // 根据 format 参数决定返回的响应格式
        if ("0".equals(format)) {
            // 返回 XML 格式的响应
            String xmlResponse = convertToXml(null, links);
            return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xmlResponse);
        } else {
            // 默认返回 JSON 格式的响应
            CommonResponse<CommonResponse.Link> response = CommonResponse.createForSuccess(0, "添加书籍成功", links);
            return response;
        }
    }


    // 根据 ID 删除书籍
    @DeleteMapping("/books/{bookId}")
    public Object deleteBook(@PathVariable int bookId, @RequestParam(defaultValue = "1") String format) {
        bookService.deleteBook(bookId);
        List<CommonResponse.Link> links = createLinks();
        CommonResponse<CommonResponse.Link> response = CommonResponse.createForSuccess(0, "删除书籍成功", links);

        if ("0".equals(format)) {
            String xmlResponse = convertToXml(response);
            return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xmlResponse);
        } else {
            return response;
        }
    }

    // 根据 ID 更新书籍
    @PutMapping("/books/{bookId}")
    public Object updateBook(@PathVariable int bookId, @RequestBody Book book ,@RequestParam(defaultValue = "1") String format) {
        book.setBookId(bookId);
        bookService.updateBook(book);
        List<CommonResponse.Link> links = createLinks();
        CommonResponse<CommonResponse.Link> response = CommonResponse.createForSuccess(0,"更新书籍成功",links);
        if("0".equals(format)){
            String xmlResponse = convertToXml(response);
            return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xmlResponse);
        }else{
            return response;
        }
    }

    @GetMapping("/books")
    public Object getBookList(@RequestParam(defaultValue = "0") int pageNum,
                                                  @RequestParam(defaultValue = "10") int pageSize,@RequestParam(defaultValue = "1") String format) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        Page<Book> page = bookService.getBookList(pageNum, pageSize);
        List<CommonResponse.Link> links = createLinks();
        CommonResponse.DataWrapper<Book> dataWrapper = new CommonResponse.DataWrapper<>(page,links);
        CommonResponse<Book> response = CommonResponse.createForSuccess(0, "Success", dataWrapper);
        if("0".equals(format)){
            String xmlResponse = convertToXml(response);
            return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xmlResponse);
        }else {
            return response;
        }
    }

    // 根据 ID 查询书籍
    @GetMapping("/books/{bookId}")
    public Object getBookById(@PathVariable int bookId, @RequestParam(defaultValue = "1") String format) {
        Book book = bookService.getBookById(bookId);
        List<CommonResponse.Link> links = createLinks();
        if (book != null) {
            if ("0".equals(format)) {
                // 返回 XML 格式的响应，这里需要你实现转换逻辑
                String xmlResponse = convertToXml(book, links);
                return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xmlResponse);
            } else {
                // 默认返回 JSON 格式的响应
                CommonResponse.DataWrapper2<Book> dataWrapper = new CommonResponse.DataWrapper2<>(book, links);
                CommonResponse<Book> response = CommonResponse.createForSuccess(0, "查询成功", dataWrapper);
                return response;
            }
        } else {
            CommonResponse response = CommonResponse.createForError("查无此书", links);
            return response;
        }
    }

}
